// pages/coach/info/info.js
var common = require('../../../utils/common.js');
Page({
  data: {
    types: [],
    coachInfo: {},
    attributes: [],
    birthday: '',
    files: [],
    indexs: { 'type': 0 }
  },
  userInfo: {},
  adjunct: [],
  tempFiles: [],
  originalFiles:[],
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.registerEvent();
    var dt = new Date();
    this.setData({
      birthday: common.formatDate(dt, 'yyyy-MM-dd'),
    });
    this.userInfo = wx.getStorageSync('userInfo');
  },
  registerEvent: function () {
    this.reqTypes();
  },
  reqTypes: function () {
    let that = this;
    common.asynPost(common.API.user.types, {}, function (data) {
      if (data['types']) {
        that.reqCoachInfo();
        that.setData({
          types: data['types']
        });
      }
    });
  },
  reqCoachInfo: function () {
    let that = this;
    common.asynPost(common.API.user.coach, {}, function (data) {
      let index = 0;      
      let coachType = that.data.types[index].id;
      if (data['coachInfo']) {
        for (var i = 0, len = that.data.types.length; i < len; i++) {
          if (that.data.types[i].id == data['coachInfo'].coachType) {
            index = i;
            break;
          }
        }
        data['coachInfo'] && that.setData({
          coachInfo: data['coachInfo'],
          'indexs.type': index,
          files:(data['coachInfo'].adjunct ? data['coachInfo'].adjunct.split('|') : []),
          birthday:(common.formatDate(new Date(data['coachInfo'].birthday.replace(/-/g,'/').replace('T',' ')),'yyyy-MM-dd'))
        });
        that.originalFiles = that.data.files;
        coachType = data['coachInfo'].coachType;
      }
      that.reqAttribute(coachType);
    });
  },
  reqAttribute: function (typeid) {
    let that = this;
    common.asynPost(common.API.user.attributes, {
      typeId: typeid
    }, function (data) {
      var items = data['items'];
      if (items) {
        let citeIndexs = that.data.indexs;
        for (var i = 0, len = items.length; i < len; i++) {
          var item = items[i];
          if (item.options && item.selected) {
            citeIndexs[item.id.toString()] = 0;
            for (var n = 0, len = item.options.length; n < len; n++) {
              citeIndexs[item.id.toString()] = 0;
              if (item.enumId == item.options[n].id) {
                citeIndexs[item.id.toString()] = n;
                break;
              }
            }
          }
        }
        that.setData({
          attributes: items,
          indexs: citeIndexs
        });
      }
    });
  },
  typeChange: function (e) {
    let that = this;
    that.setData({
      'indexs.type': e.detail.value
    });
    var selTypeId = that.data.types[that.data.indexs['type']].id;
    that.reqAttribute(selTypeId);
    var _files = [];
    if(selTypeId == that.data.coachInfo.coachType){
      _files = that.originalFiles;
    }
    that.setData({
      files:_files
    });
  },
  attritudeChanage: function (e) {
    let that = this, id = e.currentTarget.dataset.id;
    let citeIndexs = that.data.indexs;
    citeIndexs[id] = e.detail.value;
    that.setData({
      indexs: citeIndexs
    });
  },
  birthdayChanage: function (e) {
    this.setData({
      birthday: e.detail.value
    });
  },
  submitCoachInfo: function (e) {
    let that = this;
    // 上传图片
    if (that.tempFiles && that.tempFiles.length) {
      that.uploadImage(function () {
        var data = that.formData(e.detail.value);
        that.reqCoachEdit(data);
      });
    }else{
      var data = that.formData(e.detail.value);
      that.reqCoachEdit(data);
    }
  },
  reqCoachEdit:function(info){
    let that = this;
    common.asynPost((that.data.coachInfo && that.data.coachInfo.id)?common.API.user.coachEdit:common.API.user.coachAdd,
      {'info':info},
      function(data){
        that.originalFiles = that.data.files;
        that.adjunct=[];
        wx.showToast({
          title:'信息保存成功'
        });
        if(that.userInfo.type != 2){
          that.userInfo.type = 2;
          common.setUserinfo(that.userInfo);
        }
      },function(err){
        console.log(err);
      });
  },
  formData: function (info) {
    let that = this;
    let coachType = that.data.types[that.data.indexs['type']].id;
    let data = {
      money: info.money,
      birthday: this.data.birthday,
      coachType: coachType,
      tags: info.tags,
      intro: info.intro,
      adjunct: that.adjunct,
      isTyped: that.data.coachInfo.coachType != coachType,
      attributes: []
    };
    for (var key in info) {
      if (key.indexOf('attribute') > -1) {
        let idx = key.replace('attribute', '');
        let attribute = that.data.attributes[idx];
        let value = {};
        if(attribute.selected){
          value = attribute.options[that.data.indexs[attribute.id]]
        }else{
          value = {value:info[key],id:0};
        }
        data.attributes.push({ id: attribute.id, value: value.value, enumId: value.id });
      }
    }
    return data;
  },
  uploadImage: function (submit) {
    let that = this;
    let fls = that.tempFiles; 
    if (fls) {
      for (let i = 0,len = fls.length; i < len; i++) {
        let file = fls[i];
        file && common.uploadFile(common.API.base + common.API.file.uploadImage, 'auth', file, function (data) {
          i -= len - fls.length;
          fls.splice(i - 1,1);
          that.adjunct.push(data.url);
          if (!fls.length || i == fls.length - 1) {
            typeof submit === 'function' && submit();
          }
        });
      }
    }
  },
  addImage: function () {
    let that = this;
    wx.chooseImage({
      count: 8,
      sizeType: ['compressed', 'original'],
      sourceType: ['album'],
      success: function (res) {
        that.tempFiles = that.tempFiles.concat(res.tempFilePaths);
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})